import { check } from 'meteor/check';
import { JoinServer } from 'meteor-publish-join';
import { Messages } from '/imports/models/Messages';

/**
 * 获取当前私信房间的所有消息
 * @param {Object} query
 * @param {Number} limit
 */
Meteor.publish('get.messages', function(query, limit) {
  check(query.friend_id, String);
  check(limit, Number);

  let selector = {
    user_id: Meteor.userId(),
    friend_id: query.friend_id
  };

  Counts.publish(this, 'get.messages.counts', Messages.find(selector));

  return Messages.find(selector, {
    limit: limit,
    sort: {
      createdAt: -1
    }
  });
});

/**
 * 获取分组信息，结果为数组，包含：最近一条信息，好友信息
 * TODO: 未读状态信息总数
 * @param {Object} query
 * @param {Number} limit
 */
Meteor.publish('get.group.messages', function(query, limit) {
  check(query.userId, String);
  check(limit, Number);

  const selector = {
    user_id: query.userId
  };

  const pipeline = [{
      $match: selector
    },
    {
      $sort: {
        createdAt: -1
      }
    },
    {
      $group: {
        _id: '$friend_id',
        friendId: {
          $first: '$friend_id'
        },
        recent: {
          $first: '$$ROOT'
        }
      }
    },
    {
      $lookup: {
        from: 'users',
        localField: 'friendId',
        foreignField: '_id',
        as: 'friends'
      },
    },
    {
      $addFields: {
        friend: {
          $arrayElemAt: ["$friends", 0]
        }
      }
    },
    {
      $project: {
        friends: 0,
        'friend._id': 0,
        'friend.services': 0,
        'friend.createdAt': 0
      }
    },
    {
      $limit: limit
    }
  ];

  JoinServer.publish({
    context: this,
    name: 'get.group.messages.counts',
    interval: 0,
    doJoin() {
      return Messages.aggregate(pipeline).length;
    }
  });
  
  ReactiveAggregate(this, Messages, pipeline);
});
